import React, { Component } from 'react'
import pageWithIntl from '../components/PageWithIntl'
import { bindActionCreators } from 'redux'
import { initStore } from '../store'
import Head from 'next/head'
import Router from 'next/router'
import withRedux from 'next-redux-wrapper'
import axios from '../plugins/axios'
import {
    basicConfig
} from '../static/js/config'
import dynamic from 'next/dynamic'

import { addToCard, collectGoods, cancelCollectGoods } from '../actions/detail'

const Layout = dynamic(
    import('../layouts/pc.js'))
const Catalog = dynamic(
    import('../components/pc/products/catalog.js'))
const Sort = dynamic(
    import('../components/pc/products/sort.js'))
const ProductList = dynamic(
    import('../components/pc/products/list.js'))
const ListTypeTwo = dynamic(
    import('../components/pc/products/listTypeTwo.js'))
const Page = dynamic(import('../components/pc/products/page.js'))
// import Layout from '../layouts/pc.js'
// import Catalog from '../components/pc/products/catalog.js'
// import Sort from '../components/pc/products/sort.js'
// import ProductList from '../components/pc/products/list.js'
// import ListTypeTwo from '../components/pc/products/listTypeTwo.js'
const MoreInformation = dynamic(import('../components/pc/detail/moreInformation'))
const MobileMoreInformation = dynamic(import('../components/mobile/detail/moreInformation'))
const ProductMobile = dynamic(import('../components/mobile/product/index.js'))
const LayoutsMobile = dynamic(import('../layouts/mobile.js'))

//import MoreInformation from '../components/pc/detail/moreInformation'
//import MobileMoreInformation from '../components/mobile/detail/moreInformation'
//import ProductMobile from '../components/mobile/product/index.js'
//import LayoutsMobile from '../layouts/mobile.js'

import { newDevice, setMonitor } from '../actions/home/index'
import Wapper from '../components/wapper'
import SkinTag from '../components/skinTag'


class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            listType: 1, //列表展示网格1或列表2
            currentPage: 1, //当前页码,分页开始行，1开始
            total: 0, //总页数
            size: 16, //每页产品数
            listDate: [], //列表数据
            priceMin: null, //价格区间，最小值
            priceMax: null, //价格区间，最大值
            orderBy: 'salesHigh', //排序方式：("salesHigh","销量由高到低"),("saleLow","销量由低到高"),("newest","最新上传"),("priceHigh","价格高到低"),("priceLow","价格低到高"),("storeHigh","库存高到底"),("storeLow","库存低到高")
            catalogListData: [], //catalog列表数据
            categoryId: null, //分组ID，多选，多个逗号隔开
            searchIn: null, //是否从搜索页到列表页,空不是，非空即搜索条件
            hotProducts: [],//热销产品列表
            noData: true,//true有数据
            go: 0,//是否执行获取数据
            showCatelog: false,//是否显示目录
        }
    }


    routerPush = (val) => {
        Router.push(val)
    }

    //列表展示样式
    changeListType = (val) => {
        this.setState({
            listType: val
        })
    }

    changePage = (pageNumber) => {
        this.setState({
            currentPage: pageNumber
        }, () => this.getListData())
    }

    changePageSize = (pageNumber) => {
        //手机端下拉刷新专用
        let nowData = this.state.size * pageNumber
        if (nowData < (this.state.total + this.state.size)) {
            this.setState({
                currentPage: pageNumber
            }, () => this.getListData(true))
        }
    }

    setOrderBy = (val) => {
        this.setState({
            orderBy: val,
            currentPage: 1,
        }, () => this.getListData())
    }

    catalogChange = (val) => {
        this.setState({
            categoryId: val
        }, () => this.getListData())
    }

    search = (val, a) => {
        if (a == undefined) {
            this.setState({
                priceMin: val.priceLow,
                priceMax: val.priceHight
            }, () => this.getListData())
        }else {
            this.setState({
                priceMin: val.priceLow,
                priceMax: val.priceHight
            })
        }

    }

    getCatalogList = () => {
        axios.get(basicConfig.interfaceUrl + '/shop/category/list.do', {
            params: { unLogin: true }
        })
            .then((res) => {
                if (res && res.data && res.data.success) {
                    function op(val) {
                        if (Object.prototype.toString.call(val) != '[object Array]') {
                            return val
                        } else {
                            for (let a of val) {
                                a.choose = false
                                a.title = a.name
                                a.label = a.name
                                a.value = a.name
                                op(a.subList)
                            }
                            return val
                        }
                    }
                    let q = op(res.data.data)
                    this.setState({
                        catalogListData: q,
                        showCatelog: true,
                    })
                }
            }).catch((error) => {

            });
    }

    getListData = (val) => {
        //val=true，移动端下拉刷新，push数据专用
        let preload = {
            priceMin: this.state.priceMin,
            priceMax: this.state.priceMax,
            orderby: this.state.orderBy,
            start: this.state.currentPage,
            size: this.state.size
        }
        if (this.props.home.isFb) {
            preload.toFacebook = true
        }
        if (this.state.categoryId) {
            preload.categoryId = JSON.stringify(this.state.categoryId)
        }
        if (this.state.go == 0) {

            //存在searchName说明是搜索关键词
            if (this.state.searchIn) {
                preload.itemName = this.state.searchIn
                axios.get(basicConfig.interfaceUrl + '/shop/item/search.do', {
                    params: Object.assign({}, preload, { unLogin: true }) || {}
                })
                    .then((res) => {
                        if (res.data && res.data.success) {
                            if (res.data.data && res.data.data.list.length == 0) {
                                this.setState({
                                    noData: false,
                                    listDate: res.data.data.list,
                                    total: res.data.data.total,
                                })
                            } else {
                                if (val) {
                                    let arr = this.state.listDate
                                    arr.concat(res.data.data.list)
                                    this.setState({
                                        noData: true,
                                        listDate: arr,
                                        total: res.data.data.total,
                                    })
                                } else {
                                    this.setState({
                                        noData: true,
                                        listDate: res.data.data.list,
                                        total: res.data.data.total,
                                    })
                                }
                            }
                        }

                    }).catch((error) => {

                    });
            } else {
                axios.get(basicConfig.interfaceUrl + '/shop/item/list.do', {
                    params: Object.assign({}, preload, { unLogin: true })
                })
                    .then((res) => {
                        if (res.data && res.data.success) {
                            if (res.data.data && res.data.data.list.length == 0) {
                                this.setState({
                                    noData: false,
                                    listDate: res.data.data.list,
                                    total: res.data.data.total,
                                })
                            } else {
                                if (val) {
                                    let arr = this.state.listDate
                                    arr = arr.concat(res.data.data.list)
                                    this.setState({
                                        noData: true,
                                        listDate: arr,
                                        total: res.data.data.total,
                                    })
                                } else {
                                    this.setState({
                                        noData: true,
                                        listDate: res.data.data.list,
                                        total: res.data.data.total,
                                    })
                                }
                            }
                        }
                    }).catch((error) => {

                    });
            }
        }


    }

    componentDidMount() {
        if (this.props.searchName) {
            this.setState({
                searchIn: this.props.searchName,
                go: this.state.go++
            }, () => {
                this.setState({
                    go: this.state.go--
                }, () => {
                    this.getListData()
                })
            })
        }
        if (this.props.type) {
            let orderBy
            if (this.props.type == 'top') {
                orderBy = 'salesHigh'
            } else if (this.props.type == 'new') {
                orderBy = 'newest'
            }
            this.setState({
                orderBy: orderBy,
                go: this.state.go++
            }, () => {
                this.setState({
                    go: this.state.go--
                }, () => {
                    this.getListData()
                })
            })
        }
        if (this.props.categoryId) {
            let arr = []
            arr.push(this.props.categoryId)
            this.setState({
                categoryId: arr,
                go: this.state.go++
            }, () => {
                this.setState({
                    go: this.state.go--
                }, () => {
                    this.getListData()
                })
            })
        }
        this.getListData()
        this.getCatalogList()
    }
    componentWillReceiveProps(nextProps) {
        if (nextProps.type) {
            if (this.props.type != nextProps.type) {
                let orderBy
                if (nextProps.type == 'top') {
                    orderBy = 'salesHigh'
                } else if (nextProps.type == 'new') {
                    orderBy = 'newest'
                }
                this.setState({
                    orderBy: orderBy,
                    currentPage: 1,
                }, () => this.getListData())
            }
        } else {
            //异常处理，当路由存在排序，清空路由排序时只需
            if (this.props.type) {
                this.setState({
                    orderBy: 'salesHigh'
                }, () => this.getListData())
            }
        }
        if (nextProps.searchName) {
            if (nextProps.searchName != this.props.searchName) {
                this.setState({
                    searchIn: nextProps.searchName
                }, () => this.getListData())
            }
        } else {
            this.setState({
                searchIn: null
            })
        }

        if (nextProps.categoryId) {
            if (nextProps.categoryId != this.props.categoryId) {
                let arr = []
                arr.push(nextProps.categoryId)
                this.setState({
                    categoryId: arr,
                }, () => this.getListData())
            }
        } else {
            if (this.state.categoryId || (this.state.searchIn && !nextProps.searchName)) {
                //处理异常进入方式,后面是搜索然后点目录全部分类
                this.setState({
                    categoryId: null,
                    searchIn: nextProps.searchName || null
                }, () => this.getListData())

            } else {
                this.setState({
                    categoryId: null
                })
            }

        }

    }

    componentWillUnmount() {

    }

    shouldComponentUpdate(nextProps, nextState) {
        return true

    }

    render() {
        const { products, headers } = this.props
        const { device, skin } = this.props.home;

        let searchName = this.props.searchName;
        if (!searchName) {
            searchName = ''
        }
        if (this.props.home.device == 'mobile') {
            return (
                <LayoutsMobile>
                    <SkinTag {...this.props.home}></SkinTag>
                    <Head>
                        <title>PRODUCTS-{headers.bottomInfo.name}</title>
                    </Head>
                    <ProductMobile
                        {...this.props.home}
                        products={products}
                        data={this.state}
                        search={this.search}
                        searchIn={this.searchIn}
                        changePage={this.changePage}
                        size={this.state.size}
                        showCatelog={this.state.showCatelog}
                        currentPage={this.state.currentPage}
                        total={this.state.total}
                        listData={this.state.listDate}
                        noData={this.state.noData}
                        setOrderBy={this.setOrderBy}
                        changePageSize={this.changePageSize}
                        catalogListData={this.state.catalogListData}
                        categoryId={this.state.categoryId}
                        catalogChange={this.catalogChange}
                    />
                    {
                        (searchName && products.listDate.length == 0) ? <MobileMoreInformation /> : null
                    }
                </LayoutsMobile>
            )
        } else {
            return (
                <Layout>
                    <SkinTag {...this.props.home}></SkinTag>
                    <Head>
                        <title>PRODUCTS-{headers.bottomInfo.name}</title>
                    </Head>
                    <div className='productPage productPage-pc'>
                        {
                            this.state.searchIn ? '' :
                                <div className='left-part'>
                                    {
                                        !this.state.showCatelog ? '' :
                                            <Catalog
                                                search={this.search}
                                                skin={skin}
                                                catalogListData={this.state.catalogListData}
                                                categoryId={this.state.categoryId}
                                                catalogChange={this.catalogChange}
                                            />
                                    }

                                </div>
                        }
                        <div className={searchName == '' ? 'right-part right-part-padding' : ''}>
                            <Sort
                                skin={skin}
                                searchIn={searchName}
                                orderBy={this.state.orderBy}
                                setOrderBy={this.setOrderBy}
                                listType={this.state.listType}
                                total={this.state.total}
                                size={this.state.size}
                                currentPage={this.state.currentPage}
                                getListData={this.getListData}
                                changeListType={this.changeListType}
                            />
                            {
                                this.state.listType == 1 ?
                                    <ListTypeTwo
                                        searchIn={searchName}
                                        listData={this.state.listDate} />
                                    :
                                    <ProductList
                                        listData={this.state.listDate}
                                        father={this.props}
                                        routerPush={this.routerPush}
                                    />
                            }
                            {
                                this.state.noData ?
                                    <Page
                                        changePage={this.changePage.bind(this)}
                                        size={this.state.size}
                                        currentPage={this.state.currentPage}
                                        total={this.state.total} /> :
                                    <div className='list-no-data'>
                                        <img className="imgEmptyStyle" src='../static/img/Empty.png' />
                                        <span>No Data</span>
                                    </div>
                            }
                        </div>
                    </div>
                    {
                        (searchName && this.state.listDate.length == 0) ?
                            <div className="hot-pro"><MoreInformation /></div> : null
                    }
                </Layout>)
        }
    }
}

const mapStateToProps = ({ products, home, headers }) => ({
    products,
    home,
    headers
})

const mapDispatchToProps = (dispatch) => {
    return {
        newDevice: bindActionCreators(newDevice, dispatch),
        collectGoods: bindActionCreators(collectGoods, dispatch),
        cancelCollectGoods: bindActionCreators(cancelCollectGoods, dispatch),
        addToCard: bindActionCreators(addToCard, dispatch),
        setMonitor: bindActionCreators(setMonitor, dispatch),
    }
};

export default withRedux(initStore, mapStateToProps, mapDispatchToProps)(pageWithIntl(Wapper(Index)))